package com.jsh.erp.service.materialCategory;

import com.jsh.erp.datasource.entities.CategoryValidation;
import com.jsh.erp.datasource.entities.User;
import com.jsh.erp.datasource.mappers.CategoryValidationMapper;
import com.jsh.erp.service.user.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CategoryValidationService {
    @Resource
    private CategoryValidationMapper ruleMapper;
    @Resource
    private UserService userService;

    
    @Transactional(rollbackFor = Exception.class)
    public int save(Map<String, Object> val) {
        // 1. 参数校验
        Assert.notNull(val, "输入数据不能为空");

        // 2. 获取当前用户，并处理可能的异常
        User user;
        try {
            user = userService.getCurrentUser();
        } catch (Exception e) {
            throw new RuntimeException("获取当前用户失败", e);
        }

        // 3. 提取并校验 categoryId
        Object categoryIdObj = val.get("categoryId");
        Assert.notNull(categoryIdObj, "类别异常：categoryId不能为空");
        Long categoryId = Long.valueOf(categoryIdObj.toString());

        // 4. 处理 auditData 字符串（支持类似 "[1,1,1,1,1]" 或 "【1,1,1,1,1】" 格式）
        String auditDataStr = String.valueOf(val.get("auditData")).trim();
        if ((auditDataStr.startsWith("[") && auditDataStr.endsWith("]"))
                || (auditDataStr.startsWith("【") && auditDataStr.endsWith("】"))) {
            auditDataStr = auditDataStr.substring(1, auditDataStr.length() - 1);
        }

        // 将字符串按逗号分割，并去除空白字符
        String[] auditData = Arrays.stream(auditDataStr.split(","))
                .map(String::trim)
                .filter(s -> !s.isEmpty())
                .toArray(String[]::new);

        // 5. 新增前先删除该类别之前的所有记录
        this.deleteByCateId(categoryId);

        // 6. 构造待新增的 CategoryValidation 列表
            //如果没有data就不要新增了
        if (auditDataStr.isEmpty()) {
            return 1;
        }
        List<CategoryValidation> validations = Arrays.stream(auditData)
                .map(data -> {
                    CategoryValidation cv = new CategoryValidation();
                    cv.setCategoryId(categoryId);
                    cv.setFieldName(data);
                    cv.setRequired(1);
                    cv.setCreateUser(user.getId());
                    cv.setCreateTime(LocalDateTime.now());
                    cv.setDeleteFlag("0");
                    return cv;
                })
                .collect(Collectors.toList());

        // 7. 批量插入数据 validations.size()==0?1:
        return ruleMapper.batchInsert(validations);
    }



    private void deleteByCateId(Long categoryId) {
        ruleMapper.deleteByCategoryId(categoryId);
    }


    @Transactional
    public int update(CategoryValidation rule) {
        return ruleMapper.updateByPrimaryKeySelective(rule);
    }

    
    @Transactional
    public int delete(Long id) {
        return ruleMapper.deleteByPrimaryKey(id);
    }

    
    public CategoryValidation findById(Long id) {
        return ruleMapper.selectByPrimaryKey(id);
    }

    
    public List<CategoryValidation> findByCategoryId(Long categoryId) {
        return ruleMapper.selectByCategoryId(categoryId);
    }

    
    public List<CategoryValidation> findAll() {
        return ruleMapper.selectAll();
    }
}